package com.mymorningroutine;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;

import com.mymorningroutine.server.ActivityTable;
import android.widget.*;
import android.app.*;
import android.content.*;
import android.view.*;
import android.graphics.*;
import android.net.*;
import android.database.*;
import android.graphics.drawable.*;
import android.provider.*;
import java.io.*;
import android.util.*;
import java.util.*;
import android.os.*;

public class ActivityDetailActivity extends Activity
{
	private Integer itemId ;
	private com.mymorningroutine.obj.Activity activity;
	private static final int SELECTED_PICTURE = 4;
	private static final int SELECTED_AUDIO = 5;
	private TextView textTitleView;

	private TextView textDescriptionView;

	private TextView textDurationView;

	private TextView textDaysView;

	private TextView textBackgroundView;

	private TextView textPostponeView;

	private TextView textVolumeView;
	
	private EditText editTextTitle;

	private EditText editTextDescription;

	private NumberPicker editTextDuration;

	private ActivityTable activityTable;

	private TextView textAlarmView;

	private NumberPicker editTextPostpone;
	
	private SeekBar editSeekbarVolume;
	
	public String[] days;
	
	private boolean[] _selection;


	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		getActionBar().setHomeButtonEnabled(true);
		getActionBar().setDisplayShowHomeEnabled(true);
		
		setContentView(R.layout.activity_activity_detail);
		activityTable = Singleton.getActivityTable(getApplicationContext());
		days = getResources().getStringArray(R.array.daysValues);
		Intent i = getIntent();
		Integer itemId = i.getIntExtra("activityId", 0);
		this.itemId = itemId;
		_selection = new boolean[days.length];
		if(itemId > 0) {
			
			activity = activityTable.getActivity(itemId);
		}else{
			activity = new com.mymorningroutine.obj.Activity();
		}

		setTitle(activity.getTitle());
		editTextTitle = new EditText(this);
		editTextDescription = new EditText(this);
		editTextDuration = new NumberPicker(this);
	  	editTextDuration.setMinValue(1);
		editTextDuration.setMaxValue(360);
		editTextPostpone = new NumberPicker(this);
	  	editTextPostpone.setMinValue(1);
		editTextPostpone.setMaxValue(60);
		editSeekbarVolume = new SeekBar(this);
		editSeekbarVolume.setMax(100);
		editSeekbarVolume.setProgress(activity.getVolume());

		updateDetails();

		
		final AlertDialog.Builder alertDialogBuilder = new AlertDialog. Builder(ActivityDetailActivity.this);
		
		
		LinearLayout titleLAyout = (LinearLayout) findViewById(R.id.layout_title);
		alertDialogBuilder. setTitle(getResources().getString(R.string.activity_title)) ;
		alertDialogBuilder
			. setView(editTextTitle)
			. setPositiveButton(getResources().getString(R.string.save) , new DialogInterface. OnClickListener() {
				public void onClick(DialogInterface dialog, int id)
				{
					textTitleView.setText(editTextTitle.getText());
					activity.setTitle(editTextTitle.getText().toString());
				}
			})
			. setNegativeButton(getResources().getString(R.string.cancel) , new DialogInterface. OnClickListener() {
				public void onClick(DialogInterface dialog, int id)
				{
					dialog.cancel() ;
				}
			}) ;
	 final	AlertDialog alertDialogTitle = alertDialogBuilder.create();
		titleLAyout.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View p1)
				{

					
					
					alertDialogTitle.show();
				}
			});

		LinearLayout descriptionLAyout = (LinearLayout) findViewById(R.id.layout_description);
		alertDialogBuilder. setTitle(getResources().getString(R.string.activity_description)) ;
		alertDialogBuilder
			. setView(editTextDescription)
			. setCancelable(false)
			. setPositiveButton(getResources().getString(R.string.save) , new DialogInterface. OnClickListener() {
				public void onClick(DialogInterface dialog, int id)
				{
					textDescriptionView.setText(editTextDescription.getText());
					activity.setDescription(editTextDescription.getText().toString());
					//	activityTable.updateActivity(activity);
				}
			})
			. setNegativeButton(getResources().getString(R.string.cancel) , new DialogInterface. OnClickListener() {
				public void onClick(DialogInterface dialog, int id)
				{
					dialog.cancel() ;
				}
			}) ;
		final AlertDialog alertDialogDescription = alertDialogBuilder.create();
		
		
		descriptionLAyout.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View p1)
				{
					
					alertDialogDescription.show();
				}
			});

		LinearLayout durationLAyout = (LinearLayout) findViewById(R.id.layout_duration);
		
		alertDialogBuilder. setTitle(getResources().getString(R.string.activity_duration)) ;
		alertDialogBuilder
			. setView(editTextDuration)
			. setCancelable(false)
			. setPositiveButton(getResources().getString(R.string.save), new DialogInterface. OnClickListener() {
				public void onClick(DialogInterface dialog, int id)
				{
					textDurationView.setText(editTextDuration.getValue() + " minutes");
					activity.setDurationMins(editTextDuration.getValue());
				}
			})
			. setNegativeButton(getResources().getString(R.string.cancel) , new DialogInterface. OnClickListener() {
				public void onClick(DialogInterface dialog, int id)
				{
					dialog.cancel();
				}
			}) ;
		final	AlertDialog alertDialogDuration = alertDialogBuilder.create();
		durationLAyout.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View p1)
				{
					
					alertDialogDuration.show();
				}
			});


		LinearLayout postponeLAyout = (LinearLayout) findViewById(R.id.layout_postpone_time);
		alertDialogBuilder. setTitle(getResources().getString(R.id.text_postpone_time)) ;
		alertDialogBuilder
			. setView(editTextPostpone)
			. setCancelable(false)
			. setPositiveButton(getResources().getString(R.string.save) , new DialogInterface. OnClickListener() {
				public void onClick(DialogInterface dialog, int id)
				{
					textPostponeView.setText(editTextPostpone.getValue() + " minutes");
					activity.setPostponeTime(editTextPostpone.getValue());
				}
			})
			. setNegativeButton(getResources().getString(R.string.cancel) , new DialogInterface. OnClickListener() {
				public void onClick(DialogInterface dialog, int id)
				{
					dialog.cancel();
				}
			}) ;
		
		LinearLayout volumeLAyout = (LinearLayout) findViewById(R.id.layout_volume);
		alertDialogBuilder. setTitle(getResources().getString(R.string.activity_volume)) ;
		alertDialogBuilder
			. setView(editSeekbarVolume)
			. setCancelable(false)
			. setPositiveButton(getResources().getString(R.string.save) , new DialogInterface. OnClickListener() {
				public void onClick(DialogInterface dialog, int id)
				{
					textVolumeView.setText(editSeekbarVolume.getProgress() + "%");
					activity.setVolume(editSeekbarVolume.getProgress());
				}
			})
			. setNegativeButton(getResources().getString(R.string.cancel) , new DialogInterface. OnClickListener() {
				public void onClick(DialogInterface dialog, int id)
				{
					dialog.cancel();
				}
			}) ;
			
		final AlertDialog alertDialogVolume = alertDialogBuilder.create();


		volumeLAyout.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View p1)
				{

					alertDialogVolume.show();
				}
			});
			
			
		final AlertDialog alertDialogPostpone = alertDialogBuilder.create();
		
		
		postponeLAyout.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View p1)
				{
					
					alertDialogPostpone.show();
				}
			});
			
		LinearLayout daysLAyout = (LinearLayout) findViewById(R.id.layout_days);
		alertDialogBuilder
			.setTitle(getResources().getString(R.string.activity_days ))
			.setMultiChoiceItems( days, _selection, new DialogSelectionClickHandler() )
			.setPositiveButton( getResources().getString(R.string.save), new DialogButtonClickHandler() )
			.setNegativeButton(getResources().getString(R.string.cancel) , new DialogInterface. OnClickListener() {
				public void onClick(DialogInterface dialog, int id)
				{
					dialog.cancel();
				}
			});

	final	AlertDialog alertDialogDays = alertDialogBuilder.create();
		
		
		daysLAyout.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View p1)
				{
					
						alertDialogDays.show();
				}
			});
			
		
			
		LinearLayout backgroundLayout = (LinearLayout) findViewById(R.id.layout_background);
		backgroundLayout.setOnClickListener(new View.OnClickListener(){



				@Override
				public void onClick(View p1)
				{
					// TODO: Implement this method
					Intent intent = new Intent();
					intent.setType("image/*");
					intent.setAction(Intent.ACTION_GET_CONTENT);
					intent.addCategory(Intent.CATEGORY_OPENABLE);
					startActivityForResult(intent, SELECTED_PICTURE);
				}


			});
		LinearLayout musicAlarmLayout = (LinearLayout) findViewById(R.id.layout_alarm);
		musicAlarmLayout.setOnClickListener(new View.OnClickListener(){



				@Override
				public void onClick(View p1)
				{

					Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
					startActivityForResult(intent, SELECTED_AUDIO);
				}});


		Button buttonCancel = (Button) findViewById(R.id.button_cancel);
		buttonCancel.setOnClickListener(new View.OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					finish();
				}




			});

		Button buttonSave = (Button) findViewById(R.id.button_save_activity);
		buttonSave.setOnClickListener(new View.OnClickListener(){

				@Override
				public void onClick(View p1)
				{
					// TODO: Implement this method
					boolean saved = false;
					if(activity.getId() > 0){
						saved = activityTable.updateActivity(activity);
					}else {
						saved = activityTable.insertActivity(activity);
						
					}
					
					if (saved)
					{
						Toast.makeText(getApplicationContext(), getResources().getString(R.string.message_saved), Toast.LENGTH_SHORT);
						finish();
					}
					else
					{
						Toast.makeText(getApplicationContext(), getResources().getString(R.string.message_not_saved), Toast.LENGTH_SHORT);
					}
				}




			});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		// TODO: Implement this method
		getMenuInflater().inflate(R.menu.activity_detail,menu);
		return super.onCreateOptionsMenu(menu);
	}


	
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		if(data == null || resultCode != Activity.RESULT_OK){
			return;
		}
		Uri uri=data.getData(); 
		String TAG = "ActivityDetailActivity";
Log.v(TAG,uri.getPath());
		switch (requestCode)
		{
			case SELECTED_PICTURE:
				
				
					
					String[]projection={MediaStore.Images.Media.DATA};

					Cursor cursor=getContentResolver().query(uri, null, null, null, null);
				
					
					if(cursor != null && cursor.moveToFirst()){
					cursor.moveToFirst();

					int columnIndex=cursor.getColumnIndex(projection[0]);
					Log.e("idx", columnIndex + " ");
					String filePath=cursor.getString(columnIndex);
					Log.e("file", filePath);
					cursor.close();

					//	Bitmap yourSelectedImage=BitmapFactory.decodeFile(filePath);
					//	Drawable d=new BitmapDrawable(yourSelectedImage);
					textBackgroundView.setText(filePath);
					activity.setBackgroundFilePath(filePath);
					//	activityTable.updateActivity(activity);
					} else{
						
					String filePath = uri.getPath();
					Bitmap b = BitmapFactory.decodeFile(filePath);
					if(b != null){
					textBackgroundView.setText(filePath);
					activity.setBackgroundFilePath(filePath);
					} else{
						Toast.makeText(getApplicationContext(), "Please select a picture", Toast.LENGTH_SHORT);
					}
					}
				/*	
				try
				{
					InputStream inputStream = getContentResolver().openInputStream(uri);
					BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
					StringBuilder stringBuilder = new StringBuilder();
					String line;
					try
					{
						while ((line = reader.readLine()) != null)
						{
							stringBuilder.append(line);
						}
						inputStream.close();
						
					}
					catch (IOException e)
					{}

				//	FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
					
					Log.e("file", stringBuilder.toString());
					
				}
				catch (FileNotFoundException e)
				{
					Toast.makeText(getApplicationContext(), "File Not Found",Toast.LENGTH_SHORT);
				}*/

				break;
			case SELECTED_AUDIO:
				String[] proj = { MediaStore.Images.Media.DATA,
					MediaStore.Images.Media.TITLE};
				Cursor  musiccursor = managedQuery(uri, proj, null, null, null);
				Integer music_column_index = musiccursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
				musiccursor.moveToFirst();
				String filename = musiccursor.getString(music_column_index);
				//	String songTitle = musiccursor.getString(musiccursor.getColumnIndex(
				textAlarmView.setText(musiccursor.getString(musiccursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
				activity.setMusicFilePath(uri.toString());
				//activityTable.updateActivity(activity);

				break;

			default:
				break;
		}


	}


	@Override
	protected void onResume()
	{
		super.onResume();
		updateDetails();
	}



	@Override
	public boolean onOptionsItemSelected(MenuItem menuItem)
	{
		// TODO: Implement this method
		switch (menuItem.getItemId()) {
			case android.R.id.home:
				finish();
				break;
			
		}
		return super.onOptionsItemSelected(menuItem);


		
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item)
	{
		// TODO: Implement this method
		switch(item.getItemId()){
			case R.id.action_delete_activity:
				AlertDialog. Builder alertDialogBuilder = new AlertDialog. Builder(ActivityDetailActivity.this);
// set title
				alertDialogBuilder. setTitle(getResources().getString(R.string.activity_title)) ;
// set dialog message
				alertDialogBuilder
					. setCancelable(true)
					.setMessage(R.string.confirmation_delete_activity)
					. setPositiveButton(getResources().getString(R.string.ok) , new DialogInterface. OnClickListener() {
						public void onClick(DialogInterface dialog, int id)
						{
// if this button is clicked, close
// current activity
							//Delete activity
							Singleton.getActivityTable(getApplicationContext()).deleteActivity(activity.getId());
							finish();
						}
					})
					. setNegativeButton(getResources().getString(R.string.cancel) , new DialogInterface. OnClickListener() {
						public void onClick(DialogInterface dialog, int id)
						{
// if this button is clicked, just close
// the dialog box and do nothing
							dialog.cancel() ;
						}
					}) ;
// create alert dialog
				AlertDialog alertDialog = alertDialogBuilder.create();
// show it
				alertDialog.show();

				break;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	
	
	protected void updateDetails()
	{

			if (activity != null)
			{
				textTitleView = (TextView) findViewById(R.id.textTitle);
				textTitleView.setText(activity.getTitle());
				editTextTitle.setText(activity.getTitle());

				textDescriptionView = (TextView) findViewById(R.id.textDescription);
				textDescriptionView.setText(activity.getDescription());
				editTextDescription.setText(activity.getDescription());

				textDurationView = (TextView) findViewById(R.id.textDuration);
				textDurationView.setText(activity.getDurationMins() + " minutes");
				editTextDuration.setValue(activity.getDurationMins());


				textPostponeView = (TextView) findViewById(R.id.textPostponeTime);
				textPostponeView.setText(activity.getPostponeTime() + " minutes");
				editTextPostpone.setValue(activity.getPostponeTime());

				textDaysView = (TextView) findViewById(R.id.textDays);
				String days = "";
				List<Day> daysList = Arrays.asList(Day.values());
				for (Day day : activity.getDays())
				{
					if (day != null)
					{
						days += Day.getName(day) + ", ";
						_selection[daysList.indexOf(day)] = true;
					}
				}
				textDaysView.setText(days);

				textBackgroundView = (TextView) findViewById(R.id.textBackground);
				
				if(activity.getBackgroundFilePath()!= null && !activity.getBackgroundFilePath().isEmpty()){
					textBackgroundView.setText(activity.getBackgroundFilePath());
					Log.e("background",activity.getBackgroundFilePath());
				}
				
				textVolumeView = (TextView) findViewById(R.id.textVolume);
				textVolumeView.setText(activity.getVolume());
				editSeekbarVolume.setProgress(activity.getVolume());

				textAlarmView = (TextView) findViewById(R.id.textAlarm);
				if (activity.getMusicFilePath() != null && !activity.getMusicFilePath().isEmpty())
				{
					

					
					Log.v("music", activity.getMusicFilePath());

					String[] projection = { MediaStore.Audio.Media._ID, 
						MediaStore.Audio.Media.ARTIST,
						MediaStore.Audio.Media.TITLE,
						MediaStore.Audio.Media.DATA, 
						MediaStore.Audio.Media.DISPLAY_NAME,
						MediaStore.Audio.Media.DURATION};

					Cursor musiccursor = managedQuery(Uri.parse(activity.getMusicFilePath()), 
													  projection, null, null, null);
					if (musiccursor != null)
					{							  
						musiccursor.moveToFirst();
						textAlarmView.setText(musiccursor.getString(musiccursor.getColumnIndex(MediaStore.Audio.Media.TITLE)));
					}
				}

			}
	}

	public class DialogSelectionClickHandler implements DialogInterface.OnMultiChoiceClickListener
	{
		public void onClick( DialogInterface dialog, int clicked, boolean selected )
		{
		
		}
	}
	

	public class DialogButtonClickHandler implements DialogInterface.OnClickListener
	{
		public void onClick( DialogInterface dialog, int clicked )
		{
			switch( clicked )
			{
				case DialogInterface.BUTTON_POSITIVE:
					activity.getDays().clear();
					for(int i = 0; i< days.length; i ++){
						if(_selection[i]){
							activity.getDays().add(Day.values()[i]);
						}
						
					}
					textDaysView.setText(Day.getTableTextFromDays(activity.getDays()));
					break;
			}
		}
	}
	
	
}
